package com.demo.library.service.Impl;

import com.demo.library.Dao.BookRepository;
import com.demo.library.entity.Book;
import com.demo.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookRepository bookRepository;

    @Override
    public List<Book> findAll() {
        return bookRepository.findAll();
    }

    @Cacheable(cacheNames = "book", key = "#id")
    @Override
    public Book findById(Long id) {
        return bookRepository.getById(id);
    }

    @Cacheable(cacheNames = "book", key = "#result.id")
    @Override
    public Book save(Book book) {
        bookRepository.save(book);
        return  book;
    }

    @CachePut(value = "book", key = "#result.id")
    @Override
    public Book update(Book book) {
        bookRepository.save(book);
        return book;
    }

    @CacheEvict(value = "book", key = "#id")
    @Override
    public void deleteById(Long id) {
        bookRepository.deleteById(id);
    }

    @Override
    public List<Book> findByTitle(String title) {
        return bookRepository.findByTitleContains(title.trim());
    }

    @Override
    public String getPublisherNameById(Long id) {
        Book book = bookRepository.getById(id);
        if (book != null) {
            return book.getPublisher().getPublisherName();
        }
        return null;
    }

    @Override
    public List<String> findAuthorList() {
        return bookRepository.getAuthorList();
    }
}
